<?php
class ArticleAction extends Action{
	
	public function view(){
		//获取文章
		$Post = new PostsModel();
		$Article = $Post->relation(true)->where('pid='.intval($_GET['id']))->find();
		$Article['content'] = gzdecode($Article['content']);
		$this->assign('title',$Article['title']);
		$this->assign('article',$Article);
		
		//获取评论
		$Comments = new CommentModel();
		$list = $Comments->relation(true)->PostAllComment($Article['pid']);
		$this->assign('list',$list);
		$this->display();
	}
	
	public function Edit(){
		$Post = new PostsModel();
		$Article = $Post->relation(true)->where('pid='.intval($_GET['id']))->find();
		
		$this->display();
	}
	
	public function add(){
//		看下是否有相应的用户存在
		$User= M('User');
		if(preg_match('/^[0-9]+$/',trim($_POST['qq']))){
			$UserInfo = $User->where("qq='".trim($_POST['qq'])."'")->find();
		}elseif (preg_match('/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/',$_POST['email'])){
			$UserInfo = $User->where("email='".trim($_POST['email'])."'")->find();
		}else {
			$this->error('发布报道必须填写您的QQ或者是邮箱<br />请放心，该QQ或者是邮箱不会对外公布！');
		}
		
//		如果没有该用户资料，添加到数据库
		if (empty($UserInfo)) {
			$User->create();
			$uid = $User->add();
		}else{
			if (!empty($_POST['nickname'])) {
				$data['nickname'] = trim($_POST['nickname']);
			}
			if (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/",trim($_POST['url']))) {
				$data['url'] = trim($_POST['url']);
			}
			!empty($data)?$User->where('uid='.$UserInfo['uid'])->save($data):'';
			$uid = $UserInfo['uid'];
		}
		
		$data=array();
		$data['title']=$_POST['title'];
		$data['uid']=$uid;
		$data['see']=1;
		$data['posttime']=time();
		$data['Content']=array(
			'content'=>$_POST['content']
		);
		
		if (empty($_POST['content'])) {
			$this->error('报道内容不能为空！');
		}
		
		$Posts = new PostsModel();
		
		if (!$Posts->addPosts($data)) {
			$this->success($Posts->getError());
		}else {
			$this->success('添加报道成功！');
		}
		
	}
	
}